<template>
  <div>
    <el-form
      :model="ruleForm"
      status-icon
      :rules="rules"
      ref="ruleForm"
      label-width="100px"
      class="demo-ruleForm"
    >
      <el-form-item label="图书名称" prop="name">
        <el-input v-model="ruleForm.name"></el-input>
      </el-form-item>

      <el-form-item label="图书封面" prop="img">
        <el-upload
          class="upload-demo"
          drag
          :auto-upload="false"
          :on-change="handleFileChange"
          :on-success="successUpload"
          action="#"
          :show-file-list="false"
        >
          <div class="image-container" v-if="!ruleForm.img">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
              将文件拖到此处，或<em>点击上传</em>
            </div>
            <div class="el-upload__tip" slot="tip">
              只能上传jpg/png文件，且不超过500kb
            </div>
          </div>
          <div class="image-container" v-else>
            <img
              :src="'http://localhost:8888/api/files/' + ruleForm.img"
              alt="图书封面"
              class="detail-image"
            />
            <div class="image-actions">
              <el-button type="text" @click.stop="previewImage(ruleForm.img)">
                <i class="el-icon-zoom-in"></i>
              </el-button>
              <el-button type="text" @click.stop="removeImage()">
                <i class="el-icon-delete"></i>
              </el-button>
            </div>
          </div>
        </el-upload>
      </el-form-item>
      <el-form-item label="图书作者" prop="author">
        <el-input v-model="ruleForm.author"></el-input>
      </el-form-item>
      <el-form-item label="图书价格" prop="price">
        <el-input v-model="ruleForm.price"></el-input>
      </el-form-item>
      <el-form-item label="图书出版社" prop="press">
        <el-input v-model="ruleForm.press"></el-input>
      </el-form-item>
      <el-form-item label="图书介绍">
        <div id="editor"></div>
      </el-form-item>
      <!-- 状态 -->
      <el-form-item label="状态" prop="status">
        <el-select v-model="ruleForm.status" placeholder="请选择">
          <el-option label="启售" value="1"></el-option>
          <el-option label="禁售" value="0"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="图书分类" prop="typeName">
        <el-select v-model="ruleForm.bookType" placeholder="请选择">
          <el-option
            v-for="item in bookTypes"
            :label="item.name"
            :value="item.id"
            :key="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button v-if="!isEdit" type="primary" @click="handleSubmit()"
          >新增</el-button
        >
        <el-button v-if="isEdit" type="primary" @click="handleSubmit()"
          >保存修改</el-button
        >
        <el-button @click="resetForm()">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 图片预览 -->
    <el-image-viewer
      v-if="showViewer"
      :z-index="9999"
      :on-close="closeViewer"
      :url-list="[ruleForm.img]"
    ></el-image-viewer>

 
  </div>
</template>

<script>
import { saveBook } from "../../../../api/sys/book";
import { uploadFile } from "../../../../api/sys/common";
import { getAllBookTypes } from "../../../../api/sys/bookType";
import E from "wangeditor";

export default {
  name: "BookDrawer",
  props: {
    record: {
      type: Object,
      default: function () {
        return {};
      },
    },
    isEdit: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      ruleForm: {
        id: "",
        name: "",
        author: "",
        img: "",
        price: "",
        status: "",
        press: "",
        bookType: "", //图书分类id
        content: "", //图书介绍
      },
      editorVisiable: false, // 编辑器是否可见
      showViewer: false, //图片预览
      bookTypes: [],
      wangEditorInstance: null, // 存储WangEditor实例
      rules: {
        name: [
          { required: true, message: "请输入图书名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        img: [{ required: true, message: "请上传图书封面", trigger: "blur" }],
        author: [
          { required: true, message: "请输入作者姓名", trigger: "blur" },
          {
            min: 2,
            max: 20,
            message: "长度在 2 到 20 个字符",
            trigger: "blur",
          },
        ],
        price: [
          { required: true, message: "请输入图书价格", trigger: "blur" },
          {
            type: "number",
            message: "价格需为有效数字",
            transform: (value) => Number(value),
            trigger: "blur",
          },
          {
            validator: (rule, value, callback) => {
              if (value <= 0) {
                callback(new Error("价格需大于0"));
              } else {
                callback();
              }
            },
            trigger: "blur",
          },
        ],
        press: [
          { required: true, message: "请输入图书出版社", trigger: "blur" },
          {
            min: 2,
            max: 50,
            message: "长度在 2 到 50 个字符",
            trigger: "blur",
          },
        ],
        status: [{ required: true, message: "请选择状态", trigger: "change" }],
        bookType: [
          { required: true, message: "请选择图书分类", trigger: "change" },
        ],
      },
    };
  },
  watch: {
    record: {
      handler(val) {
        console.log("Record prop changed:", val);
        if (val && Object.keys(val).length > 0) {
          this.initForm(val);
          // 编辑模式下设置编辑器内容
          if (this.wangEditorInstance) {
            this.wangEditorInstance.txt.html(val.content || "");
          }
        } else {
          this.resetForm();
          // 新增模式下清空编辑器内容
          if (this.wangEditorInstance) {
            this.wangEditorInstance.txt.html("");
          }
        }
      },
      immediate: true,
      deep: true,
    },
  },
  mounted() {
    // 获取所有图书分类
    this.getBookTypes();
    // 初始化WangEditor
    this.initEditor();
  },
  beforeDestroy() {
    // 销毁WangEditor实例
    if (this.wangEditorInstance) {
      this.wangEditorInstance.destroy();
      this.wangEditorInstance = null;
    }
  },

  methods: {
    // 初始化WangEditor
    initEditor() {
      this.$nextTick(() => {
        if (!this.wangEditorInstance) {
          this.wangEditorInstance = new E("#editor");
          this.wangEditorInstance.config.placeholder = "请输入内容";
          this.wangEditorInstance.config.uploadFileName = "file";
          this.wangEditorInstance.config.uploadImgServer = "http://localhost:8888/api/files/wang/upload";
          this.wangEditorInstance.create();
          // 初始化时设置内容
          this.wangEditorInstance.txt.html(this.record.content || "");
        }
      });
    },
   
    //初始化表单
    initForm(val) {
      this.ruleForm = {
        id: val.id,
        name: val.name,
        img: val.img,
        author: val.author,
        price: val.price,
        press: val.press,
        status: val.status !== undefined ? String(val.status) : "",
        bookType: val.bookType !== undefined ? val.bookType : "",
        content: val.content || "",
      };
      this.showViewer = false;
    },
    //获取所有图书分类
    async getBookTypes() {
      try {
        const res = await getAllBookTypes();
        if (res.code === 200) {
          this.bookTypes = res.data.list;
        } else {
          this.$message.error(res.message || "获取图书分类失败");
        }
      } catch (error) {
        console.error("获取图书分类失败", error);
      }
    },
    //提交表单
    async handleSubmit() {
      try {
        // 表单验证
        await this.$refs.ruleForm.validate();

        this.loading = true;

        // 准备提交数据
        const submitData = { ...this.ruleForm };
        if (this.wangEditorInstance) {
          submitData.content = this.wangEditorInstance.txt.html();
        }

        // let res = {};
        // 提交请求
        const res = await saveBook(submitData);

        if (res.code === 200) {
          this.$message.success(this.isEdit ? "编辑成功" : "新增成功");
          this.$emit("success");
          this.$emit("close");
        } else {
          this.$message.error(
            res.message || (this.isEdit ? "编辑失败" : "新增失败")
          );
        }
      } catch (error) {
        console.error("提交表单失败", error);
      } finally {
        this.loading = false;
      }
    },
    resetForm() {
      this.ruleForm = {
        id: "",
        name: "",
        img: "",
        author: "",
        price: "",
        press: "",
        status: "1",
        bookType: "",
        content:""
      };
    },
    successUpload(res) {
      console.log(res);
      this.ruleForm.img = res.data;
    },
    //上传图片
    async handleFileChange(file) {
      let rawFile = null;

      if (file.raw && file.raw instanceof File) {
        rawFile = file.raw;
      } else if (file instanceof File) {
        rawFile = file;
      } else {
        this.$message.error("文件格式错误");
        return;
      }

      try {
        const res = await uploadFile(rawFile);

        if (res.code === 200) {
          this.ruleForm.img = res.data;
          this.uploadProgress = 100;
          this.$message.success("图片上传成功");

          // 延迟隐藏进度条
          setTimeout(() => {
            this.uploadProgress = 0;
          }, 1000);
        } else {
          this.$message.error(res.message || "上传失败");
          this.uploadProgress = 0;
        }
      } catch (error) {
        console.error("上传失败", error);
        this.$message.error("图片上传失败");
        this.uploadProgress = 0;
      }
    },
    //删除图片
    removeImage() {
      this.ruleForm.img = "";
    },
    //关闭预览
    closeViewer() {
      this.showViewer = false;
      this.ruleForm.img = "";
    },
  },
};
</script>

<style scoped>
.image-container {
  border: 1px solid #eee;
  border-radius: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  position: relative;
  height: 100%;
  width: 100%;
}

.detail-image {
  height: 100%;
  width: 100%;
  object-fit: cover;
}
/* 他会控该区域的内容，不会被其他元素覆盖，包括内部的按钮可加性 */
.image-actions {
  position: absolute; /* 绝对定位 */
  top: 0;
  left: 0;
  right: 0;
  bottom: 0; /* 覆盖整个父容器 */
  background: rgba(0, 0, 0, 0.5); /* 半透明黑色背景 */
  display: flex; /* 弹性布局 */
  align-items: center; /* 垂直居中 */
  justify-content: center; /* 水平居中 */
  opacity: 0; /* 默认透明 */
  transition: opacity 0.3s; /* 透明度过渡效果 */
}

.image-container:hover .image-actions {
  opacity: 1; /* 鼠标悬停时显示 */
}

.image-actions .el-button {
  color: white; /* 按钮文字颜色 */
  height: 50px;
  width: 50px;
  border-radius: 50%;
  font-size: 16px; /* 按钮图标大小 */
}

.image-actions .el-button:hover {
  background: rgba(255, 255, 255, 0.2); /* 按钮悬停时背景色 */
}
</style>
